import React, { useEffect } from 'react'
import '../../components/dark/index.scss'

function Index() {
  // 处理主题变化的函数
  const handleThemeChange = (newTheme: string | null) => {
    document.documentElement.className = newTheme || 'light';
  }

  // 监听存储变化和初始化主题
  useEffect(() => {
    // 存储事件处理函数
    const storageHandler = (e: StorageEvent) => {
      if (e.key === "theme") {
        handleThemeChange(e.newValue);
      }
    }

    // 初始化主题
    const initialTheme = localStorage.getItem("theme") || "light";
    handleThemeChange(initialTheme);

    // 添加存储事件监听器
    window.addEventListener("storage", storageHandler);

    // 清理函数：组件卸载时移除事件监听器
    return () => {
      window.removeEventListener("storage", storageHandler);
    }
  }, []); // 空依赖数组，仅在组件挂载时执行

  // 切换主题的函数
  const toggleTheme = () => {
    const newTheme = document.documentElement.className === "dark" ? "light" : "dark";
    document.documentElement.className = newTheme;
    localStorage.setItem("theme", newTheme);
  }

  return (
    <div className='login'>
      登录
      <button onClick={toggleTheme}>变色</button>
      
    </div>
  )
}

export default Index